//
//  YYEUserAccountViewModel.swift
//  weibo14
//
//  Created by mac on 16/3/5.
//  Copyright © 2016年 mac. All rights reserved.
//  链接登陆view和模型的的vm

import UIKit

class YYEUserAccountViewModel: NSObject {
    
    // 当前模型视图引用的模型
    var account:YYEUserAccount?{
    
        didSet{
            print("外界赋值了")
        }
    }
    
    
    // 判断当前帐户的accessToken是否过期,如果过期return true/ 否则 false
    var isExpiresIn:Bool {
        
//        print(NSDate())
//        print(account!.expiresDate!)
        
        if NSDate().compare(account!.expiresDate!) == .OrderedAscending {
            
            
            return false
        }
        
        
        return true
    }
    
    // 返回授权码 只读属性

    var accessToken: String? {
      return  account?.access_token
    }
    
    // 判断用户是否登陆
    var  uesrLogon:Bool {
        
        if  accessToken != nil && !self.isExpiresIn {
            return true
        }
        return false
    }
    
    // 提供一个单利的方法  数据是从沙盒中读取的
    static let  sharedAccountViewModel:YYEUserAccountViewModel = {
    
        let vm = YYEUserAccountViewModel()
        // 需调用vm的方法
        vm.account = vm.loadAccount()
        
        return vm
    }()
    
    // 归档与解档路径 转成oc的类型操作的
    private let archiveFile = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
    
    // 解档函数
    private func loadAccount()->YYEUserAccount? {
     
        return NSKeyedUnarchiver.unarchiveObjectWithFile(archiveFile) as? YYEUserAccount
    }
    
    // 保存用户信息
    private func saveUserAccount(userAccount :YYEUserAccount) {
    
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: archiveFile)
    }
    
    // 请求accessToken
    // 再有授权码的时候
    func loadAccessToken( code:String ,callBack:(issucceed:Bool)->() ) {
    
        // 请求地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 请求的参数
        let parameters = [
            "client_id": WB_APPKEY,
            "client_secret": WB_APPSECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri":WB_REDIRECT_URI
        ]
     //   YYENetworkTools.sharedTools.requst(<#T##method: YYERequestMethod##YYERequestMethod#>, urlString: <#T##String#>, parameters: <#T##AnyObject?#>, callback: <#T##YYERequestCallback##YYERequestCallback##(responseObject: [String : AnyObject]?, error: NSError?) -> ()#>)
        
        YYENetworkTools.sharedTools.requst(.POST, urlString: urlString, parameters: parameters) { (responseObject, error) -> () in
            
            if error != nil {
            
                print("\(error)")
            
                callBack(issucceed: false)
                
                return
            }
           // 请求的数据不对
            
           // Optional(["grant_type": authorization_code, "client_id": 295758514, "client_secret": e50e75c1d6de23b9385c75d676669e32, "code": 3fb137f855e10fdf450ad78f8ccc1990, "redirect_uri": http://yangye.com])
            // print(responseObject)
            // 进行字典转模型,并且获取用户的个人信息
            let account = YYEUserAccount(dict: responseObject!)
            // print(account)
        
            
            // 获取用户的信息
            self.loadUserInfo(account, callBack: callBack)
        }
        
    }
    
    
    func loadUserInfo(account:YYEUserAccount,callBack:(issucceed:Bool)->()) {
    
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // 守护一下 参数不够
        guard let access_token = account.access_token , uid = account.uid else {
        
            print("参数不够")
            callBack(issucceed: false)
            return
        }
        
//        guard let accessToken = account.access_token, uid = account.uid else {
//            print("参数不够")
//            callback(isSuccess: false)
//            return
//        }
        
        let parameter = [
            "access_token" :access_token,
            "uid":uid
        ]
        //YYENetworkTools.sharedTools.requst(.POST, urlString: urlString, parameters: parameters)
        YYENetworkTools.sharedTools.requst(.GET, urlString: urlString, parameters: parameter) { (responseObject, error) -> () in
            
            if error != nil {
            
                print("请求失败")
                callBack(issucceed: false)
                return
            }
            
            account.screen_name = responseObject!["screen_name"] as? String
            account.avatar_large = responseObject!["avatar_large"] as? String
            
          
            
            // 存储个人信息
            
            // 2. 保存用户的登录的模型(以便下次进入软件的时候,直接使用)
            
            
            // 归档
            
            // 归档的路径
            self.saveUserAccount(account)
            // 能当前视图模型身上的模型赋值
            self.account = account
            
            // 回调闭包,说登录成功
            callBack(issucceed: true)
            
            
        }
    }
    
    
}




